# == Schema Information
#
# Table name: orders
#
#  id                             :integer          not null, primary key
#  uuid                           :string
#  width                          :integer
#  height                         :integer
#  expected_square                :float            default(0.0)
#  booking_date                   :datetime         not null
#  rate                           :float
#  total                          :float
#  remark                         :string
#  state                          :string
#  courier_number                 :string
#  install_date                   :datetime
#  cgj_company_id                 :integer
#  cgj_customer_id                :integer
#  cgj_facilitator_id             :integer
#  cgj_customer_service_id        :integer
#  material                       :string
#  material_id                    :integer
#  workflow_state                 :string
#  public_order                   :boolean
#  square                         :float
#  mount_order                    :boolean
#  serial_number                  :string
#  is_company                     :boolean
#  measure_amount                 :float
#  install_amount                 :float
#  manager_confirm                :boolean
#  region                         :string           default("CRM")
#  terminal_count                 :float
#  amount_total_count             :float
#  basic_order_tax                :integer
#  measure_amount_after_comment   :integer
#  installed_amount_after_comment :integer
#  measure_comment                :integer
#  measure_raty                   :float
#  installed_raty                 :float
#  service_measure_amount         :float
#  service_installed_amount       :float
#  basic_tax                      :float
#  deduct_installed_cost          :float
#  deduct_measure_cost            :float
#  sale_commission                :integer
#  intro_commission               :integer
#  user_id                        :integer          not null
#  account_id                     :integer          not null
#  customer_id                    :integer          not null
#  created_at                     :datetime         not null
#  updated_at                     :datetime         not null
#  introducer_name                :string
#  introducer_tel                 :string
#  introducer_id                  :integer
#  province                       :string
#  city                           :string
#  area                           :string
#  region_id                      :string
#  store_id                       :string
#  estimated_total                :float            default(0.0)
#  rebate                         :float            default(0.02)
#  measure_master                 :string
#  is_sync                        :boolean          default(FALSE)
#

class Order < ActiveRecord::Base

	# CGJ serial_number
	# 介绍人 完成订单生成介绍人，执行策略
	#   estimated_total: 
	#   rebate: 介绍人默认返利0.02

	STATE = { 
		'new' 										=> '新订单',
		'appointed_measurement' 	=> '预约测量', 
		'measured' 								=> '已测量',
		'appointed_installation' 	=> '预约安装', 
		'installed' 							=> '已安装', 
		'completed' 							=> '完成交易', 
		'canceled'								=> '已取消', 
		'confirm_installed' 			=> '管理员已确认安装'
	}

	belongs_to :user
	belongs_to :account
	belongs_to :customer

	belongs_to :introducer, foreign_key: "introducer_id", class_name: 'User'
	has_one :strategy_result, class_name: 'StrategyResult'

	belongs_to :_region, foreign_key: "region_id", class_name: 'Region'
	belongs_to :store

	delegate :province, :city, :area, :street, :tel, :name, to: :customer
  has_many :pictures, as: :pictureable

	scope :last_week, -> { where('created_at>=?',  1.week.ago) }
	scope :this_month, -> { where('created_at>=?',  Time.now.beginning_of_month) }
	scope :completed, -> { where('workflow_state=?', "completed")}
	scope :pre_completed, -> { where('workflow_state not in (?)', ['canceled', 'completed'])} # 计算预收入的提成

	after_update :execute_strategy

	def sync_cgj
		res = Cgj.create_order(cgj_hash)
		_hash = JSON res.body
		if _hash["code"] == 200
			_order = _hash["order"].except("id", "created_at", "updated_at", "customer_id")
			(attributes.keys & _order.keys).each do |ele|
				self.send("#{ele}=", _order[ele]) 
			end
			self.booking_date 						= Time.at(_order["booking_date"].to_i)
			self.install_date 						= Time.at(_order["install_date"].to_i)
			self.cgj_company_id 					= _order["company_id"]
			self.cgj_facilitator_id 			= _order["facilitator_id"]
			self.cgj_customer_service_id  = _order["customer_service_id"]
			self.save

			# self.customer.update_attributes({
			# 	longitude: 	_order["longitude"],
			# 	latitude: 	_order["latitude"],
			# 	address: 		_order["address"],
			# 	tel:        _order["tel"],
			# 	province:   _order["province"],
			# 	city:       _order["city"],
			# 	area:       _order["area"],
			# 	street:  		_order["street"],
			# 	user_id: 		self.user_id
			# })
		else
			Rails.logger.info "*" * 100
			Rails.logger.info _hash
			Rails.logger.info "*" * 100
		end
	end

	def execute_strategy
		if completed?
			_hash = {order_id: id}
			# 获取策略
			strategy = account.get_valid_strategy(province, city, area)

			if strategy
				_hash[:strategy_id] 			= strategy.id
				# saler
				_hash[:saler_id] 					= user_id
				_hash[:saler_rate_amount] = estimated_total * strategy.rate.to_f
				# saler_director
				if user.director
					_hash[:saler_director_id] = user.director_id
					_hash[:saler_director_rate_amount] = estimated_total * strategy.saler_director_rate.to_f
				end
				# introducer
				if introducer
					_hash[:introducer_id] = introducer_id
					_hash[:introducer_rebate_amount] = estimated_total*rebate.to_f
				end
				# cs_director
				if account.cs_director
					_hash[:cs_director_id] = account.cs_director.id
					_hash[:cs_director_amount] = estimated_total * strategy.cs_rate.to_f
				end
			end

			# 渠道策略
			if region_strategy
				_hash[:region_strategy_id] = region_strategy.id
				# operator
				if store
					_hash[:operator_id] = store.admin_id
					_hash[:operator_amount] = estimated_total * region_strategy.store_rate.to_f
				end
				# planinger_director
				if region.planinger_director
					_hash[:planinger_director_id] = region.planinger_director.id
					_hash[:planinger_director_amount] = estimated_total * region_strategy.plan_rate.to_f
				end
			end
			StrategyResult.create(_hash) if strategy
		end
	end

	def region_strategy
		RegionStrategy.where(region_id: region_id).first
	end

	def completed?
		workflow_state == 'completed'
	end

	def show_strategy_result
		_ary = [['产品预估价格', estimated_total], ['提成', order_price]]
		_ary << ['介绍人返利', strategy_result.introducer_rebate_amount] if completed? && strategy_result

		_ary
	end



  ##根据门店的提成比率
  def store_rate
    self.store.try(:rate).to_f
  end

	def show_rate_amount
		if !['canceled', 'completed'].include?(workflow_state)
			strategy = account.get_valid_strategy(province, city, area)
			strategy ? (estimated_total.to_f * strategy.rate.to_f).round(2) : 0.0
		elsif completed?
			strategy_result.try(:saler_rate_amount).to_f
		else
			0.0
		end
	end

  def self.search_order(key=nil)
    Order.joins(:customer).where(["serial_number LIKE :key OR customers.tel LIKE :key OR  customers.name LIKE :key", key: "%#{key}%"])
  end

  def pictures_info
    self.pictures.as_json
  end

	def cgj_hash
		{
			square: 				expected_square,
			province: 			province,
			city: 					city,
			area: 					area,
			street: 				street,
			# tel: 						tel,
			# name: 					name,
			tel: 						user.mobile,
			name: 					user.name,
			booking_date: 	booking_date.to_i,
			customer_service_id: cgj_customer_service_id,
			mount_order: 		mount_order,
			total: 					total,
			company_id: 		cgj_company_id,
			material: 			material,
			material_id: 		material_id,
			order_no: 			id,
			customer_id: 		user.cgj_user_id, # 窗管家用户ID
			region: 				region,
			remark: 				remark
		}
	end

	def company
		Company.find_by_cgj_id cgj_company_id
	end


	def to_hash
		{
			serial_number:  serial_number,
			company_name:   company.try(:name),
			square: 				expected_square,
			province: 			province,
			city: 					city,
			area: 					area,
			street: 				street,
			tel: 						tel,
			name: 					name,
			owner_name: 		user.try(:name),
			booking_date: 	booking_date.strftime("%F %T"), #.getlocal
			workflow_state: STATE[workflow_state],
			measure_master: measure_master,
			mount_order: 		mount_order,
			measure_amount: measure_amount,
			total: 					total,
			company_id: 		cgj_company_id,
			material: 			material,
			material_id: 		material_id,
			id: 						id,
			customer: 			user_id,
      pictures_info: pictures_info,
			region: 				region,
			region_name:    _region.try(:full_name),
      store_name: 		self.store.try(:name),
			estimated_total: estimated_total,
      store_rate: self.store.try(:rate).to_f,
			rebate: 				 rebate,
			_source: 				 is_sync ? 'cgj' : '',
			state:           completed? ? '已完成' : '未完成',
			strategy_result: show_strategy_result,
      order_price: order_price,
      created_at: self.created_at.to_s
		}
	end


  ### 2018-5-10 开始
  ### 站内交易支付
  ####
  def pay_order(user)
    if self.workflow_state == "completed"
      return false, "订单已经结算过了"
    end
    ActiveRecord::Base.transaction do 
      p = WalletLog.new(pay_user(user))
      u = WalletLog.new(income_user)
      p.save!
      u.save!
      self.update_columns(workflow_state: "completed")
      return true, :ok
    end
  rescue  Exception => e
    return false, "失败 #{e}"
  end

  def order_price
    (self.store.try(:rate).to_f / 100 * self.estimated_total.to_f).round(2)
  end

  ##要收钱的的人
  def income_user
    options = {
      transfer: 2,
      state: 1,
      trade_type: "local",
      amount: order_price,
      total: user.wallet_total + order_price,
      user_id: user.id
    }
    options
  end

  #付钱的人
  def pay_user(p_user)
    options = {
      transfer: 1,
      state: 1,
      trade_type: "local",
      user_id: p_user.id,
      amount: order_price,
      total: p_user.wallet_total - order_price
    }
    options
  end




end
